﻿using UnityEngine;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Net
{
    public partial class AsycUdpClient
    {
        public void Connect(string ip, int tcpPort, int udpPort)
        {
            if (Connected) return;

            tcpAdress = new IPEndPoint(IPAddress.Parse(ip), tcpPort);
            udpAdress = new IPEndPoint(IPAddress.Parse(ip), udpPort);

            //启动连接线程
            Thread connect = new Thread(ConnectThread);
            connect.Start();
        }
        
        
        void ConnectThread()
        {
            try
            {
                tcpSocket = new TcpClient();
                udpSocket = new UdpClient();

                tcpSocket.Connect(tcpAdress);
                udpSocket.Connect(udpAdress);

                //Read accepted ID
                byte[] buff = new byte[4];
                NetworkStream s = tcpSocket.GetStream();

                for (int i = 0; i < buff.Length; i++)
                    buff[i] = (byte)s.ReadByte();

                //Send it back
                myID = BitConverter.ToInt32(buff, 0);
                udpSocket.Send(buff, 4);

                //启动接收数据线程
                receiveThread = new Thread(ReceiveThread);
                
                //启动发送数据线程
                sendThread = new Thread(SendThread);
                
                //TCP心跳线程？
                aliveThread = new Thread(AliveThread);

                receiveThread.Start();
                sendThread.Start();
                aliveThread.Start();

                OnConnect();
            }
            catch (Exception e)
            {
                CatchException(e);
                Disconnect();
            }
        }
    }
}

